/**
 * Ingenius-Group S.A.S
 *
 * Project: SAU
 * File: AbstractService.java
 * Date: 01/03/2011
 */

package com.ingenius.sau.server.service;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ingenius.sau.client.Constants;
import com.ingenius.sau.server.persistence.DAO;
import com.ingenius.sau.shared.model.core.BaseBean;
import com.ingenius.sau.shared.util.filter.Filter;

/**
 * Class <strong>AbstractService</strong>
 * 
 * @author Jesus David
 * @version 0.1
 */
@SuppressWarnings("serial")
public abstract class AbstractService extends RemoteServiceServlet {

	protected Logger getLogger(Class<?> clazz) {
		if (clazz == null) {
			throw new IllegalArgumentException("Class for logger is required.");
		}
		return Logger.getLogger(clazz.getName());
	}

	protected String getUsername() {
		String userID = (String) getSession().getAttribute(
				Constants.COOKIE_USER_ID);

		System.out.println("Server --> UserID: " + userID);
		return userID;
	}

	protected HttpSession getSession() {
		return getThreadLocalRequest().getSession();
	}

	protected void checkPermutationStrongName() throws SecurityException {
		return;
	}

	@SuppressWarnings("unchecked")
	public <T extends BaseBean> PagingLoadResult<T> find(DAO<T> dao,
			List<Filter> filters, BasePagingLoadConfig config) {

		try {
			String orderBy = null;

			if (filters == null) {
				filters = new ArrayList<Filter>();
			}
			if (config == null) {
				config = new BasePagingLoadConfig();
			}
			if (config.getSortInfo().getSortField() != null) {
				orderBy = config.getSortInfo().getSortField() + " "
						+ config.getSortInfo().getSortDir();
			}
			int start = config.getOffset();
			int recordsCount = dao.count(filters).intValue();
			int limit = recordsCount;

			if (config.getLimit() > 0) {
				limit = Math.min(start + config.getLimit(), recordsCount);
			}

			List<T> result = dao.getRange(filters, orderBy, start, limit);
			for (T object : result) {
				object = (T) object.toDTO();
			}
			return new BasePagingLoadResult<T>(result, start, recordsCount);

		} catch (Exception e) {
			e.printStackTrace();
			return new BasePagingLoadResult<T>(new ArrayList<T>(), 0, 0);
		}
	}
}
